import Vue from 'vue'
import store from '@/store'
import user from '../api/common/user';

//声明一个全局方法
Vue.prototype.$isLogin = () => {
	return store.state.isLogin; //是否登录
}

Vue.prototype.$userinfo = () => {
	return store.state.userinfo; //用户信息
}
Vue.prototype.$needAuth = () => {
	return store.state.needAuth; //是否需要授权
}

Vue.prototype.$setIsLogin = (isLogin) => {
	store.state.isLogin = isLogin;
}

Vue.prototype.$setUserinfo = (userinfo) => {
	store.state.userinfo = userinfo;
}

Vue.prototype.$setNeedAuth = (needAuth) => {
	store.state.needAuth = needAuth;
}

Vue.prototype.$login = () => {
	//Promise 执行顺序
	return new Promise((resolve, reject) => {
		wx.login({
			success(res) {
				Vue.prototype.$log(res);
				Vue.prototype.$u.api.login({
					appid: Vue.prototype.$appid,
					code: res.code
				}).then(res2 => {
					Vue.prototype.$log(res2.data.token);
					
					uni.setStorageSync('token', res2.data.token);
					if (res2.code === 200) {
						Vue.prototype.$setIsLogin(true);
						Vue.prototype.$setNeedAuth(false);
						Vue.prototype.$setUserinfo(res2.data.user);
					}
					resolve(res2);
				}).catch(err => {
					reject(err)
				})
			},
			fail(err) {
				reject(err)
			}
		})
	})
}
Vue.prototype.$auth = () => {

	return new Promise((resolve, reject) => {
		if(!Vue.prototype.$needAuth()){
			Vue.prototype.$log('无需授权');
			resolve(true);
			return;
		}
		
		wx.getUserProfile({
			desc: '用于完善会员资料',
			success: (res) => {
				Vue.prototype.$log(res);
				let userinfo = {
					nickname: res.userInfo.nickName,
					avatar: res.userInfo.avatarUrl
				}
				Vue.prototype.$u.api.auth(userinfo).then(res2 => {
					Vue.prototype.$log(res2);
					if (res2.code === 200) {
						Vue.prototype.$setNeedAuth(false);
						Vue.prototype.$setIsLogin(true);
						resolve(true);
					} else {
						reject(false);
					}
				})
			},
			fail(err) {
				reject(err);
			}
		})
	})

}

Vue.prototype.$gzhLogin=()=>{
	return new Promise(async (resolve,reject)=>{
		if(Vue.prototype.$isLogin()){
			resolve(true);
			return; //必须加
		}
		let url = window.location.href;
		if(!Vue.prototype.$u.test.contains(url,'?')){
			resolve(true);
			return; //必须加
		}
		let code = url.split('?')[1].split('&')[0].split('=')[1];
		let res = await Vue.prototype.$u.api.gzhlogin({
			code: code
		})
		Vue.prototype.$log(res);
		if(res.code===200){
			uni.setStorageSync('token',res.data&&res.data.token);
			Vue.prototype.$setUserInfo(res.data&&es.data.user);
			Vue.prototype.$setIsLogin(true);
			resolve(true);
		}else{
			reject(false);
		}
	})
}